package com.tuanbiao.utils;

import android.os.Environment;

import com.abiao.lib_utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/4/26 10:25
 */
public final class TxtUtils {
    public final static String TEMP = getRoot() + "/tuanbiao/temp/";
    public final static String FILE_CACHE = TEMP + "file/";
    public final static String AUTHORIZED_FILE_CACHE = FILE_CACHE + "authorized/";
    public final static String BLAST_DIR = Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/blast";
    private static List<File> mList = new ArrayList<>();

    public static List<File> getAllTxt() {
        mList.clear();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File path = Environment.getExternalStorageDirectory();// 获得SD卡路径
            File[] files = path.listFiles();// 读取
            getFileName(files);
        }
        return mList;
    }

    public static void getFileName(File[] files) {
        if (files != null) {// 先判断目录是否为空，否则会报空指针
            for (File file : files) {
                if (file.isDirectory()) {
                    String s = file.getAbsolutePath();
                    //除去当前离线授权目录
                    if (StringUtils.equals(s, AUTHORIZED_FILE_CACHE.substring(0, AUTHORIZED_FILE_CACHE.length() - 1)) ||
                            StringUtils.equals(s, BLAST_DIR)) {
                        break;
                    }
                    Timber.i(s);
                    getFileName(file.listFiles());
                } else {
                    String fileName = file.getName();
                    if (fileName.endsWith(".txt")) {
                        mList.add(file);
                    }
                }
            }
        }
    }

    public static String getRoot() {
        String root = Environment.getExternalStorageDirectory()
                .getAbsolutePath();
        if (root.endsWith("/")) {
            root = root.substring(0, root.length() - 1);
        }
        return root;
    }
}
